package cn.starrysky108.simpleerp.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

/**
 * springContext工具类
 *
 * @author Carl Lee
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static SpringContextUtil instance;
    private ApplicationContext applicationContext;

    public SpringContextUtil() {
        //赋值给静态对象
        instance = this;
    }

    /**
     * 通过名字获取上下文中的bean
     *
     * @param name bean名称
     */
    public static Object getBean(String name) {
        return instance.applicationContext.getBean(name);
    }

    /**
     * 通过类型获取上下文中的bean
     *
     * @param requiredType bean类型
     * @param <T>          泛型
     */
    public static <T> T getBean(Class<T> requiredType) {
        return instance.applicationContext.getBean(requiredType);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}